import 'package:flutter/material.dart';
import 'package:flutter_study/util/log.dart';

import '../list/my_listview.dart';

class MyDialogRoute extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return MyDialogRouteState();
  }

}

class MyDialogRouteState extends State<MyDialogRoute> {
  List<String> options = List.generate(10, (index){
    return "选项${index+1}";
  });

  @override
  Widget build(BuildContext context) {
    return SafeArea(child: Scaffold(
      body: Column(
        children: [
          ElevatedButton(
            onPressed: (){
              _showDialog();
            },
            child: Text("显示屏幕居中 Dialog"),
          ),
          ElevatedButton(
            onPressed: (){
              _showAlertDialog();
            },
            child: Text("显示屏幕居中 AlertDialog"),
          ),
          ElevatedButton(
            onPressed: (){
              _showSimpleDialog();
            },
            child: Text("显示屏幕居中 SimpleDialog, 左右离屏幕会有间距"),
          ),
          ElevatedButton(
            onPressed: () async {
              int? res = await _showBasicModalBottomSheet(options);
              Log.i("基础底部弹窗：选中了第$res个选项");
            },
            child: Text("基础底部弹窗")
          ),
          ElevatedButton(
            onPressed: () async {
              int? res = await _showFullScreenModalBottomSheet(options);
              Log.i("全屏底部弹窗：选中了第$res个选项");
            },
            child: Text("全屏底部弹窗")
          ),
          ElevatedButton(
            onPressed: () async {
              int? res = await _showCustomModalBottomSheet(options);
              Log.i("自定义底部弹窗：选中了第$res个选项");
            },
            child: Text("自定义底部弹窗"),
          ),
        ],
      ),
    ));
  }

  /// 基础底部弹窗
  Future<int?> _showBasicModalBottomSheet(List<String> data){
    return showModalBottomSheet(
        context: context,
        isDismissible: false, // 点击遮罩是否隐藏弹窗
        builder: (context){
          return ListView.builder(
            itemBuilder: (context, index){
              return ListTile(
                title: Text(data[index]),
                onTap: (){
                  Navigator.of(context).pop(index);
                },
              );
            },
            itemCount: data.length,
          );
        }
    );
  }

  /// 全屏底部弹窗
  Future<int?> _showFullScreenModalBottomSheet(List<String> data){
    return showModalBottomSheet(
        context: context,
        isScrollControlled: true, // 是否有可滚动的子控件
        builder: (context){
          return ListView.builder(
            itemBuilder: (context, index){
              return ListTile(
                title: Text(data[index]),
                onTap: (){
                  Navigator.of(context).pop(index);
                },
              );
            },
            itemCount: data.length,
          );
        }
    );
  }

  /// 自定义底部弹窗
  Future<int?> _showCustomModalBottomSheet(List<String> data){
    return showModalBottomSheet(
      // 由于底部弹窗默认是有颜色的，因此要显示出圆角需要将底部弹窗的颜色设置为透明。
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
        ),
        context: context,
        /// 若对话框有滚动的子 view(如 ListView, GridView), 需要设置为 true, 否则设置的对话框高度会失效
        isScrollControlled: true,
        builder: (context){
          return Container( // Container 可以指定宽高，从而指定弹窗的高度,背景颜色,圆角
            height: MediaQuery.of(context).size.height / 2,
            child: Column(
              children: [
                SizedBox( // SizedBox 指定子控件的宽高
                  height: 50,
                  child: Stack(
                    textDirection: TextDirection.rtl, // 指定文本或子控件的起始排列方向
                    children: [
                      Center( // Center 将子控件居中显示,若自身的尺寸没有受到限制, 将尽可能的大
                        child: Text(
                          "底部弹窗",
                          style: TextStyle(
                            fontWeight: FontWeight.bold,
                            fontSize: 16,
                          ),
                        ),
                      ),
                      IconButton(
                        icon: Icon(Icons.close),
                        onPressed: (){
                          Navigator.of(context).pop();
                        },
                      ),
                    ],
                  ),
                ),
                Divider(height: 1),
                Expanded(
                  child: ListView.builder( // 在 Column 或 Row 内嵌套 ListView 需要对它指定大小,
                    // 使用有高度的 Container, SizedBox 或者 Expanded
                    scrollDirection: Axis.vertical,
                    itemBuilder: (context, index){
                      return ListTile(
                        title: Text(data[index]),
                        onTap: (){
                          Navigator.of(context).pop(index);
                        },
                      );
                    },
                    itemCount: data.length,
                  ),
                ),
              ],
            ),
          );
        }
    );
  }

  void _showDialog(){
    showDialog(
      context: context,
      barrierColor: Colors.amberAccent, // 遮罩层背景颜色
      builder: (ctx) {
        return Dialog(
          insetPadding: EdgeInsets.zero,  // 距离屏幕的间距
          backgroundColor: Colors.red,  // 对话框背景颜色
          shadowColor: Colors.blue, // 对话框底部阴影的颜色
          elevation: 10,  // 值越大，阴影范围越大越柔和
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(24),
          ),
          child: Container(
            height: 100,
          ),
        );
      },
    );
  }

  void _showAlertDialog(){
    showDialog(
      context: context,
      builder: (ctx) {
        return AlertDialog(
          backgroundColor: Colors.red,  // 对话框背景颜色
          shadowColor: Colors.transparent,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(24),
          ),
          title: Text("AlertDialog"),
          content: Text("Dialog content..."),
          actions: [
            Text("Cancel"),
            Text("Ok"),
            Text("Ok"),
            Text("Ok"),
            Text("Ok"),
          ],
        );
      },
    );
  }

  /// 显示简单对话框, 子组件不能是延迟加载模型的组件（如 ListView、GridView 、 CustomScrollView 等
  void _showSimpleDialog() {
    showDialog(
      context: context,
      builder: (ctx){
        return SimpleDialog(
          title: Center(
            child: Text("简单对话框"),
          ),
          titlePadding: EdgeInsets.zero,
          insetPadding: EdgeInsets.zero,
          contentPadding: EdgeInsets.zero,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(24),
          ),
          children: [
            Container(
              height: 100,
              color: Colors.red,
            ),
            Row(
              children: [
                Expanded(
                  flex: 1,
                  child: TextButton(
                    onPressed: (){
                      Navigator.pop(context);
                    },
                    child:Text("Cancel"),
                    style: ButtonStyle(
                      minimumSize: MaterialStateProperty.resolveWith<Size>((states){
                        return Size.fromHeight(100);
                      }),
                      backgroundColor: MaterialStateProperty.resolveWith<Color>((states){
                        return Colors.green;
                      }),
                      shape: MaterialStateProperty.resolveWith<OutlinedBorder>((states){
                        return RoundedRectangleBorder(
                          side: BorderSide(),
                          borderRadius: BorderRadius.only(bottomLeft: Radius.circular(24)),
                        );
                      }),
                    ),
                  ),
                ),
                Expanded(
                  flex: 1,
                  child: TextButton(
                    onPressed: (){
                      Navigator.pop(context);
                    },
                    child:Text("Ok"),
                    style: ButtonStyle(
                      minimumSize: MaterialStateProperty.resolveWith<Size>((states){
                        return Size.fromHeight(100);
                      }),
                      backgroundColor: MaterialStateProperty.resolveWith<Color>((states){
                        return Colors.grey;
                      }),
                      shape: MaterialStateProperty.resolveWith<OutlinedBorder>((states){
                        return RoundedRectangleBorder(
                          side: BorderSide(),
                          borderRadius: BorderRadius.only(bottomRight: Radius.circular(24)),
                        );
                      }),
                    ),
                  ),
                ),
              ],
            )
          ],
        );
      },
    );
  }
}